﻿using System;
using System.Collections;
using System.Windows.Forms;
using OFX.Aggregator.Infrastructure;

namespace OFX.Aggregator.Application
{
	public partial class OFXAggregatorMainForm : Form
	{
		private readonly IStatementProcessingWorkflow workflow;
		private StatementSource[] statementSources;

		public OFXAggregatorMainForm(IStatementProcessingWorkflow workflow)
		{
			this.InitializeComponent();

			SingletonContainer.Resolve<IProgressReport>
				(new Hashtable {{"progressBar", this.progressBar}});

			this.workflow = workflow;
			this.workflow.WorkflowStarted += this.workflow_WorkflowStarted;
			this.workflow.WorkflowFinished += this.workflow_WorkflowFinished;
		}

		public StatementSource[] StatementSources
		{
			get { return this.statementSources; }
			set
			{
				this.statementSources = value;

				this.comboBoxStatementSources.SelectedValue = null;
				this.comboBoxStatementSources.DataSource = this.statementSources;
			}
		}

		private void workflow_WorkflowStarted(object sender, EventArgs e)
		{
			Cursor = Cursors.WaitCursor;
		}

		private void workflow_WorkflowFinished(object sender, EventArgs e)
		{
			Cursor = Cursors.Default;
		}

		private void comboBoxStatementSources_SelectedIndexChanged(object sender, EventArgs e)
		{
			var panelLocator = SingletonContainer.Resolve<IStatementSourcePanelLocator>();
			var selectedPanelId = (string) this.comboBoxStatementSources.SelectedValue;
			var panel = (UserControl) (!string.IsNullOrEmpty(selectedPanelId) ? panelLocator.GetPanel(selectedPanelId) : null);

			this.tableLayoutPanel.SuspendLayout();

			try
			{
				Control previousControl = this.tableLayoutPanel.GetControlFromPosition(0, 1);
				if (previousControl != null)
				{
					this.tableLayoutPanel.Controls.Remove(previousControl);
				}

				if (panel != null)
				{
					this.tableLayoutPanel.Controls.Add(panel, 0, 1);
					this.tableLayoutPanel.SetColumnSpan(panel, 2);

					panel.ValidateChildren();
				}
			}
			finally
			{
				this.tableLayoutPanel.ResumeLayout();
			}
		}

		private void BankScrapingOFXForm_Activated(object sender, EventArgs e)
		{
			// TODO: Replace this with a predicate
			var selectedPanelId = (string) this.comboBoxStatementSources.SelectedValue;
			foreach (StatementSource statementSource in this.comboBoxStatementSources.Items)
			{
				if (statementSource.PanelId == selectedPanelId)
				{
					if (statementSource.Retrieval.CanRetrieveStatement())
					{
						// No need to search for a enabled StatementSource
						return;
					}
				}
			}

			foreach (StatementSource statementSource in this.comboBoxStatementSources.Items)
			{
				if (statementSource.Retrieval.CanRetrieveStatement())
				{
					this.comboBoxStatementSources.SelectedValue = statementSource.PanelId;
					break;
				}
			}
		}
	}
}